package com.ypf.delaycancelorder.controller;

import com.ypf.delaycancelorder.config.DelayedQueueConfig;
import com.ypf.delaycancelorder.entity.Order;
import com.ypf.delaycancelorder.service.IOrderService;
import com.ypf.delaycancelorder.utils.JsonResult;
import com.ypf.delaycancelorder.utils.R;
import com.ypf.delaycancelorder.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private IOrderService orderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping("/add")
    public JsonResult<Void> InsertOrder(){

        String orderNo=StringUtil.GenerateOrderNo("ypf","");
        Integer delayTime=30000;  // 30s

        Order order =new Order();
        order.setStatus(Order.pay_status_waiting);
        order.setOrderNo(orderNo);
        order.setDeleted(false);
        order.setGmtCreate(new Date());
        order.setGmtModified(new Date());
        orderService.insert(order);

        // 发送订单号给队列
        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE_NAME,DelayedQueueConfig.DELAYED_ROUTING_KEY,orderNo,msg->{
            // 设置延时时间 单位ms
            msg.getMessageProperties().setDelay(delayTime);
            return msg;
        });

        return new  JsonResult<Void>(BaseController.OK);
    }

    // 查询订单接口
    @GetMapping("/find/{orderNo}")
    public JsonResult<Order> FindByOrder(@PathVariable("orderNo") String orderNo){
        Order order = orderService.findByOrderNo(orderNo);
        return new JsonResult<>(BaseController.OK,order);
    }

    // 支付订单接口
    @PutMapping("/pay/{orderNo}")
    public JsonResult<Void> UpdateOrder(@PathVariable("orderNo") String orderNo){
        orderService.updateByOrderNo(orderNo,Order.pay_status_paid);
        return new JsonResult<>(BaseController.OK);
    }
}
